package com.start.client.app.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.start.client.app.entity.ClientAppEntity;
import com.start.client.app.entity.ClientAppVersionEntity;
import com.start.client.app.entity.ClientDownRecordEntity;
import com.start.client.app.enums.StartAppClientVersionType;
import com.start.client.app.global.DispatcherStartAppClientEvent;
import com.start.client.app.service.ClientAppService;
import com.start.client.app.service.ClientAppVersionService;
import com.start.client.app.service.ClientDownRecordService;
import com.start.client.app.vo.ClientClientAppInfo;
import com.start.common.api.Result;
import com.start.common.dataRule.DataQueryConstructor;
import com.start.common.exceptions.StartBusException;
import com.start.common.tools.IPTools;
import com.start.common.tools.SpringContextTools;
import com.start.common.tools.StartEnumTools;
import com.start.core.annotations.RegisterMenu;
import com.start.core.annotations.RegisterPermission;
import com.start.core.annotations.StartLog;
import com.start.security.annotations.DataPermission;
import com.start.security.annotations.IgnoreAuth;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;


/**
 * APP 客户端版本管理
 *
 * @author gxl
 * @email ${email}
 * @date 2021-03-09 21:14:56
 */
@RestController
@RequestMapping("app/appVersion")
@RegisterMenu(value = "APP 客户端版本管理", systemCode = "app:AppVersion", component = "views/app/appVersion/index", path = "/appVersion/index")
public class ClientAppVersionController {
    private static final String LOG_TITLE = "APP 客户端版本管理";

    @Autowired
    private ClientAppVersionService clientAppVersionService;
    @Autowired
    private ClientAppService clientAppService;

    @Autowired
    private ClientDownRecordService clientDownRecordService;


    /**
     * 列表
     */
    @GetMapping("/page")
    @DataPermission("app/appVersion/list")
    public Result<?> list(Page<ClientAppVersionEntity> page, ClientAppVersionEntity entity) {
        QueryWrapper<ClientAppVersionEntity> queryWrapper = DataQueryConstructor.createEntity(entity);
        return Result.ok(clientAppVersionService.page(page, queryWrapper));
    }


    /**
     * 信息
     */
    @GetMapping("/info/{id}")
    @StartLog(value = LOG_TITLE, action = "查询")
    @PreAuthorize("@pas.hasPermission('app:appVersion:info')")
    @RegisterPermission(value = "app:appVersion:info", name = "查看")
    public Result<?> info(@PathVariable("id") String id) {
        return Result.ok(clientAppVersionService.getById(id));
    }

    /**
     * 保存
     */
    @PostMapping("/add")
    @StartLog(value = LOG_TITLE, action = "添加")
    @PreAuthorize("@pas.hasPermission('app:appVersion:add')")
    @RegisterPermission(value = "app:appVersion:add", name = "添加")
    public Result<?> save(@RequestBody ClientAppVersionEntity appVersion) {
        if (appVersion.getAppUpdateType() == 0) {
            appVersion.setMinimumFullVersionCode(null);
        } else {
            if (appVersion.getMinimumFullVersionCode() == null) return Result.fail("增量更新请选择最低全量版本");
        }
        clientAppVersionService.save(appVersion);
        return Result.ok();
    }

    /**
     * 修改
     */
    @PutMapping("/updateById")
    @StartLog(value = LOG_TITLE, action = "修改")
    @PreAuthorize("@pas.hasPermission('app:appVersion:edit')")
    @RegisterPermission(value = "app:appVersion:edit", name = "修改")
    public Result<?> update(@RequestBody ClientAppVersionEntity appVersion) {
        clientAppVersionService.updateById(appVersion);
        return Result.ok();
    }

    /**
     * 删除
     */
    @DeleteMapping("/deleteById/{id}")
    @StartLog(value = LOG_TITLE, action = "删除")
    @PreAuthorize("@pas.hasPermission('app:appVersion:delete')")
    @RegisterPermission(value = "app:appVersion:delete", name = "删除")
    public Result<?> delete(@PathVariable("id") String id) {
        clientAppVersionService.removeById(id);
        return Result.ok();
    }

    @GetMapping("/listFullVersionByAppManageId")
    public Result<?> listFullVersionByAppManageId(String appManagerId) {
        if (StringUtils.isEmpty(appManagerId)) return Result.ok();
        return Result.ok(clientAppVersionService.listFullVersionByAppManagerId(appManagerId));
    }

    @IgnoreAuth
    @PostMapping("/checkAppUpdateV2")
    public Result<?> checkAppUpdateV2(@RequestBody ClientClientAppInfo appInfo) {
        return Result.ok(clientAppVersionService.checkAppUpdate2(appInfo));
    }

    @GetMapping("/getClientAllVersionDict")
    public Result<?> getClientAllVersionDict() {
        return Result.ok(StartEnumTools.getEnumDic(StartAppClientVersionType.class));
    }

    @IgnoreAuth
    @GetMapping("/getAppDownloadInfo")
    @CrossOrigin(origins = "*")
    public Result<?> getAppDownloadInfo(String appId, String versionType) {
        if (StringUtils.isAllBlank(versionType)) {
            versionType = "prod";
        }
        StartAppClientVersionType appVersionType = StartEnumTools.findEnumByValue(StartAppClientVersionType.class, versionType);
        if (appVersionType == null) {
            appVersionType = StartAppClientVersionType.PROD;
        }
        ClientAppEntity entity = clientAppService.getByAppId(appId);
        if (entity == null) {
            throw new StartBusException("未知app信息");
        }
        ClientAppVersionEntity version = clientAppVersionService.getMaxOneByFullVersion(entity.getId(), appVersionType);
        DispatcherStartAppClientEvent clientEvent = DispatcherStartAppClientEvent.getInstance();
        clientEvent.beforeAppDownloadInfo(appId);
        Map<String, Object> appInfo = new HashMap<>();
        appInfo.put("appInfo", entity);
        appInfo.put("versionInfo", version);
        clientEvent.afterAppDownloadInfo(entity);
        ClientDownRecordEntity downRecord = ClientDownRecordEntity.create(version, "android", IPTools.getFullIpAddr(SpringContextTools.getHttpServletRequest()));
        clientDownRecordService.save(downRecord);
        return Result.ok(appInfo);
    }
}
